<?php
include("../org_cookie.php");
$Bid = $_GET['id'] ?? '';
$Uname = $_COOKIE['NAME'] ?? '';
$enorg = $_COOKIE['enorg'] ?? '';

session_start();
include("bizyair.php");

// 读取分辨率文件
$resolutionData = [];
$resolutionFile = 'resolution.txt';
if (file_exists($resolutionFile)) {
    $resolutionData = file($resolutionFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
}

// 读取尺寸文件
$sizeData = [];
$sizeFile = 'BizyAir_size.txt';
if (file_exists($sizeFile)) {
    $sizeData = file($sizeFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
}

// 读取CSV文件
$stylesData = [];
$csvFile = '../styles.csv';
if (file_exists($csvFile)) {
    $handle = fopen($csvFile, 'r');
    if ($handle !== false) {
        // 读取标题行
        $headers = fgetcsv($handle, 0, ',', '"', '"');

        // 读取数据行
        while (($data = fgetcsv($handle, 0, ',', '"', '"')) !== false) {
            if (count($data) >= 4) {
                $stylesData[] = [
                    'name' => $data[0],
                    'prompt' => $data[1],
                    'negative_prompt' => $data[2],
                    'remark' => $data[3]
                ];
            }
        }
        fclose($handle);
    }
}

// 读取BizyAIR JSON模板文件
$templateData = [];
$jsonDir = 'json';
if (is_dir($jsonDir)) {
    $files = scandir($jsonDir);
    foreach ($files as $file) {
        if (pathinfo($file, PATHINFO_EXTENSION) === 'json') {
            $filePath = $jsonDir . '/' . $file;
            $jsonContent = file_get_contents($filePath);
            $jsonData = json_decode($jsonContent, true);
            if ($jsonData && isset($jsonData['id'])) {
                $templateData[] = $jsonData;
            }
        }
    }
}

// 按ID排序
usort($templateData, function($a, $b) {
    return $a['id'] - $b['id'];
});
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo (isset($_COOKIE['cnorg']) && $_COOKIE['cnorg']) ? $_COOKIE['cnorg'].' - ' : ''; ?> API调用工具 v1.2.3 </title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        // 浅色模式为默认（调整后）
        if (localStorage.theme === 'dark') {
            document.documentElement.classList.add('dark');
        } else {
            document.documentElement.classList.remove('dark');
        }
        
        // 切换深色/浅色模式
        function toggleTheme() {
            if (document.documentElement.classList.contains('dark')) {
                document.documentElement.classList.remove('dark');
                localStorage.theme = 'light';
            } else {
                document.documentElement.classList.add('dark');
                localStorage.theme = 'dark';
            }
        }
        
        // 表单提交处理
        function handleSubmit() {
            const submitBtn = document.getElementById('submit_btn');
            const resultStatus = document.getElementById('result_status');
            const apiKeyInput = document.getElementById('api_key');
            
            // 保存API密钥到localStorage
            if (apiKeyInput.value.trim() !== '') {
                localStorage.setItem('bizyair_api_key', apiKeyInput.value.trim());
            }
            
            // 显示加载状态
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 处理中...';
            resultStatus.innerHTML = '<div class="bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 p-4 rounded-lg"><i class="fa fa-info-circle mr-2"></i>正在处理您的请求，请稍候...</div>';
            
            // 表单提交后会由PHP处理并返回结果
        }
        
        // 将PHP数据传递给JavaScript
        window.currentConfigData = <?php echo json_encode($defaultConfig); ?>;
        window.stylesData = <?php echo json_encode($stylesData); ?>;
        window.templateData = <?php echo json_encode($templateData); ?>;
        window.enorg = <?php echo json_encode($enorg); ?>;
    </script>
    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: {
                extend: {
                    colors: {
                        primary: '#667eea',
                        secondary: '#764ba2',
                        accent: '#4fd1c5',
                        dark: {
                            100: '#e5e7eb', 200: '#9ca3af', 300: '#6b7280', 400: '#4b5563', 500: '#374151', 600: '#1f2937', 700: '#111827', 800: '#0f172a', 900: '#030712',
                        }
                    },
                    fontFamily: { sans: ['Inter', 'system-ui', 'sans-serif'], },
                    animation: { 'fade-in': 'fadeIn 0.5s ease-in-out', 'slide-up': 'slideUp 0.5s ease-out', 'pulse-slow': 'pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite', },
                    keyframes: {
                        fadeIn: { '0%': { opacity: '0' }, '100%': { opacity: '1' }, },
                        slideUp: { '0%': { transform: 'translateY(20px)', opacity: '0' }, '100%': { transform: 'translateY(0)', opacity: '1' }, }
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        .block{ color: #ddd; }
        @layer utilities {
            .content-auto { content-visibility: auto; }
            .gradient-bg { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
            .card-hover { @apply transition-all duration-300 hover:shadow-lg hover:-translate-y-1; }
            .text-gradient { @apply bg-clip-text text-transparent bg-gradient-to-r from-primary to-secondary; }
            .input-focus { @apply focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all; }
            .field-mapping-label { transition: all 0.3s ease; }
            .field-mapping-input { transition: all 0.3s ease; }
            .prompt-template-section { transition: all 0.3s ease; }
            .remark-section { transition: all 0.3s ease; }
        }
    </style>
</head>
<body class="bg-gray-50 dark:bg-dark-800 text-gray-800 dark:text-gray-100 min-h-screen font-sans transition-colors duration-300">
    <div class="flex h-screen">
        <aside id="sidebar" class="w-64 bg-white/90 dark:bg-dark-800/90 backdrop-blur-md shadow-md flex flex-col transition-all duration-300 z-50 fixed h-full">
            <div class="p-4 border-b border-gray-200 dark:border-dark-700">
                <div class="flex items-center space-x-2">
                    <i class="fa fa-paint-brush text-primary text-2xl"></i>
                    <h1 class="text-xl font-bold text-gradient" id="APItitle">&nbsp;</h1>
                </div>
            </div>
            
            <nav class="flex-1 overflow-y-auto p-4">
                <ul class="space-y-2">
                    <?php foreach ($jsonConfigs as $id => $config): 
                        $isActive = $id == $requestedId;
                        $icon = 'fa-file-image-o';
                        if (strpos(strtolower($config['name']), '放大') !== false) { $icon = 'fa-search-plus'; } 
                        elseif (strpos(strtolower($config['name']), '融合') !== false) { $icon = 'fa-object-group'; } 
                        elseif (strpos(strtolower($config['name']), '重绘') !== false) { $icon = 'fa-refresh'; }
                    ?>
                    <li>
                        <a href="?login=<?php echo htmlspecialchars($_GET['login'] ?? 'ph'); ?>&id=<?php echo $id; ?>" 
                           class="flex items-center p-3 rounded-lg hover:bg-gray-100 dark:hover:bg-dark-700 transition-colors <?php echo $isActive ? 'bg-primary/10 text-primary' : ''; ?>">
                            <i class="fa <?php echo $icon; ?> w-6 text-primary"></i>
                            <span class="truncate"><?php
                                $filename = basename($config['filename'], '.json');
                                $cleanName = preg_replace('/^\d+-/', '', $filename);
                                echo htmlspecialchars($cleanName); 
                             ?></span>
                        </a>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </nav>
            
            <div class="p-4 border-t border-gray-200 dark:border-dark-700 space-y-3">
                <button onclick="toggleTheme()" class="w-full p-3 flex items-center justify-center space-x-2 bg-gray-200 dark:bg-dark-600 rounded-lg hover:bg-gray-300 dark:hover:bg-dark-500 transition-colors">
                    <i class="fa fa-moon-o dark:hidden"></i>
                    <i class="fa fa-sun-o hidden dark:inline-block"></i>
                </button>
                <button id="toggleSidebar" class="w-full p-3 flex items-center justify-center space-x-2 bg-gray-200 dark:bg-dark-600 rounded-lg hover:bg-gray-300 dark:hover:bg-dark-500 transition-colors">
                    <i class="fa fa-chevron-left"></i>
                </button>
            </div>
        </aside>
        
        <div id="sidebarToggleBtn" class="fixed left-0 top-1/2 transform -translate-y-1/2 bg-white dark:bg-dark-700 p-3 rounded-r-lg shadow-md z-40 hidden">
            <button onclick="toggleSidebar()"><i class="fa fa-chevron-right"></i></button>
        </div>

        <main class="flex-1 ml-64 transition-all duration-300 p-8">
            <section class="gradient-bg rounded-2xl p-8 mb-10 text-white animate-fade-in">
                <div class="max-w-3xl mx-auto text-center">
                    <h1 class="text-4xl md:text-5xl font-bold mb-4"><?php echo (isset($_COOKIE['cnorg']) && $_COOKIE['cnorg']) ? $_COOKIE['cnorg'].' - ' : ''; ?>BizyAIR API调用工具</h1>
                    <p class="text-xl opacity-90 mb-6">实现从设计到部署的无缝衔接，支持多种创意图像任务   </p>
                </div>
            </section>

            <section id="form-section" class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                <div class="space-y-6 animate-slide-up">
                    <form id="api-form" method="post" enctype="multipart/form-data" onsubmit="handleSubmit();">
                        <input type="hidden" name="action" value="process">
                        
                        <div class="bg-white dark:bg-dark-700 rounded-xl shadow-md p-6 card-hover mb-6">
                            <div class="flex items-center justify-between mb-4">
                                <h2 class="text-2xl font-bold flex items-center"><i class="fa fa-cogs text-primary mr-2"></i><?php echo htmlspecialchars($defaultConfig['name']); ?> API配置</h2>
                                <input type="hidden" id="input_type" name="input_type" value="<?php echo htmlspecialchars($defaultConfig['name']); ?>">
                                <button type="button" id="toggleConfigBtn" class="flex items-center space-x-2 px-3 py-2 bg-gray-100 dark:bg-dark-600 rounded-lg hover:bg-gray-200 dark:hover:bg-dark-500 transition-colors">
                                    <i class="fa fa-eye text-primary" id="toggleIcon"></i>
                                    <span class="text-sm font-medium" id="toggleText">隐藏配置</span>
                                </button>
                            </div>
                            <div id="apiConfigSection" class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                                <div>
                                    <label for="api_key" class="block text-sm font-medium mb-1">API密钥 (可选)</label>
                                    <input type="password" id="api_key" name="api_key" placeholder="留空则使用浏览器 Cookies 中的密钥" class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-dark-500 bg-gray-50 dark:bg-dark-600 input-focus dark:text-white">
                                </div>
                                <div>
                                    <label for="web_app_id" class="block text-sm font-medium mb-1">Web App ID</label>
                                    <input type="number" id="web_app_id" name="web_app_id" value="<?php echo htmlspecialchars($defaultConfig['web_app_id']); ?>" class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-dark-500 bg-gray-50 dark:bg-dark-600 input-focus dark:text-white">
                                </div>
                            </div>
                            
                            
                            <button type="submit" id="submit_btn" class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-3 px-6 rounded-lg transition-colors flex items-center justify-center">
                                <i class="fa fa-rocket mr-2"></i>生成图片
                            </button>
                        </div>

                        <div id="inputParamsSection" class="bg-white dark:bg-dark-700 rounded-xl shadow-md p-6 card-hover mb-6">
                            <h2 class="text-2xl font-bold mb-4 flex items-center"><i class="fa fa-sliders text-primary mr-2"></i>输入参数</h2>
                            
                            <div id="text_prompt_group" style="display: <?php echo $currentConfig['text'] ? 'block' : 'none'; ?>; margin-bottom: 6px;">
                                <label for="text_prompt" class="block text-sm font-medium mb-1">文本提示词</label>
                                <textarea id="text_prompt" name="text_prompt" rows="4" placeholder="输入图像生成或修改的描述..." class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-dark-500 bg-gray-50 dark:bg-dark-600 input-focus dark:text-white mb-4"></textarea>
                                <label for="text_prompt_field" class="block text-sm font-medium mb-1 field-mapping-label">文本提示词字段映射</label>
                                <input type="text" id="text_prompt_field" name="text_prompt_field" value="<?php echo htmlspecialchars($currentConfig['text_field']); ?>" placeholder="如: 14:PrimitiveStringMultiline.value" class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-dark-500 bg-gray-50 dark:bg-dark-600 input-focus dark:text-white field-mapping-input">
                            </div>

                            <?php for ($i = 1; $i <= 5; $i++): ?>
                            <div id="image_group_<?php echo $i; ?>" class="mb-6" style="display: <?php echo $i <= $currentConfig['images'] ? 'block' : 'none'; ?>;">
                                <label class="block text-sm font-medium mb-2">图片 <?php echo $i; ?> (本地 或 URL 二选一)</label>
                                <div class="flex flex-col md:flex-row gap-4">
                                    <div class="md:w-1/2">
                                        <div class="border-2 border-dashed border-gray-300 dark:border-dark-500 rounded-lg p-6 text-center hover:bg-gray-100 dark:hover:bg-dark-600 transition-colors duration-200 h-full flex flex-col justify-center items-center">
                                            <!-- 修改accept属性以支持webp格式 -->
                                            <input type="file" id="image_<?php echo $i; ?>" name="image_<?php echo $i; ?>" accept="image/*,.webp" class="hidden" onchange="previewImageBizy(event, 'preview<?php echo $i; ?>')">
                                            <label for="image_<?php echo $i; ?>" class="cursor-pointer flex flex-col items-center">
                                                <i class="fa fa-upload text-3xl text-gray-400 mb-2"></i>
                                                <p class="text-sm">点击上传或拖放图片</p>
                                            </label>
                                            <div id="preview<?php echo $i; ?>" class="mt-4 hidden w-full relative">
                                                <img src="" alt="预览图" class="max-w-full max-h-48 mx-auto rounded-lg border border-gray-200 dark:border-dark-400">
                                                <button type="button" onclick="removeImagePreview(<?php echo $i; ?>)" class="absolute top-1 right-1 bg-red-500 hover:bg-red-600 text-white rounded-full w-6 h-6 flex items-center justify-center text-xs"><i class="fa fa-times"></i></button>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="md:w-1/2 space-y-4">
                                        <div>
                                            <label for="image_url_<?php echo $i; ?>" class="block text-sm font-medium mb-1">图片 <?php echo $i; ?> URL (可选)</label>
                                            <input type="text" id="image_url_<?php echo $i; ?>" name="image_url_<?php echo $i; ?>" placeholder="输入图片URL地址" class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-dark-500 bg-gray-50 dark:bg-dark-600 input-focus dark:text-white">
                                        </div>
                                        <div>
                                            <label for="image_<?php echo $i; ?>_field" class="block text-sm font-medium mb-1 field-mapping-label">图片 <?php echo $i; ?> 字段映射</label>
                                            <input type="text" id="image_<?php echo $i; ?>_field" name="image_<?php echo $i; ?>_field" value="<?php echo htmlspecialchars($currentConfig['image_fields'][$i-1] ?? ''); ?>" placeholder="如: 2:LoadImage.image" class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-dark-500 bg-gray-50 dark:bg-dark-600 input-focus dark:text-white field-mapping-input">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endfor; ?>

                            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div id="float_group" style="display: <?php echo $currentConfig['float'] ? 'block' : 'none'; ?>;">
                                    <label id="float_label" for="float_value" class="block text-sm font-medium mb-1">浮点数参数（倍数）</label>
                                    <input type="range" id="float_value" name="float_value" min="1" max="4" step="0.1" value="2" class="w-full h-2 bg-gray-200 dark:bg-dark-500 rounded-lg appearance-none cursor-pointer accent-primary mb-4">
                                    <div class="text-center text-sm text-gray-500 dark:text-gray-400 mb-1">当前值: <span id="float_value_display">2</span></div>
                                    <label for="float_field" class="block text-sm font-medium mb-1 field-mapping-label">浮点数字段映射</label>
                                    <input type="text" id="float_field" name="float_field" value="<?php echo htmlspecialchars($currentConfig['float_field']); ?>" placeholder="如: 99:easy float.value" class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-dark-500 bg-gray-50 dark:bg-dark-600 input-focus dark:text-white field-mapping-input">
                                </div>
                                
                                <!-- 多个整数参数组 -->
                                <?php if (!empty($currentConfig['int_fields'])): ?>
                                    <?php foreach ($currentConfig['int_fields'] as $index => $intField): ?>
                                        <div id="int_group_<?php echo $index; ?>" class="int-group" style="display: block;">
                                            <label id="int_label_<?php echo $index; ?>" for="int_value_<?php echo $index; ?>" class="block text-sm font-medium mb-1">
                                                <?php 
                                                // 根据字段类型设置标题
                                                if (strpos($intField, 'SDXLEmptyLatentSizePicker+.batch_size') !== false) {
                                                    echo '整数参数（生成批次数）';
                                                } elseif (strpos($intField, 'PrimitiveInt.value') !== false) {
                                                    echo '整数参数（最大像素）';
                                                } elseif (strpos($intField, 'KSampler.steps') !== false) {
                                                    echo '整数参数（生成步数）';
                                                } elseif (strpos($intField, 'EmptySD3LatentImage.width') !== false) {
                                                    echo '整数参数（宽度）';
                                                } elseif (strpos($intField, 'EmptySD3LatentImage.height') !== false) {
                                                    echo '整数参数（高度）';
                                                } elseif (strpos($intField, 'EmptySD3LatentImage.batch_size') !== false) {
                                                    echo '整数参数（批次）';
                                                } else {
                                                    echo '整数参数';
                                                }
                                                ?>
                                            </label>
                                            <input type="number" id="int_value_<?php echo $index; ?>" name="int_value[<?php echo $index; ?>]" value="<?php 
                                            // 根据字段类型设置默认值
                                            if (isset($defaultConfig['input_values'][$intField])) {
                                                echo (int)$defaultConfig['input_values'][$intField];
                                            } else {
                                                // 设置不同字段类型的默认值
                                                if (strpos($intField, 'SDXLEmptyLatentSizePicker+.batch_size') !== false) {
                                                    echo '4'; // 生成批次数默认值
                                                } elseif (strpos($intField, 'PrimitiveInt.value') !== false) {
                                                    echo '3072'; // 最大像素默认值
                                                } elseif (strpos($intField, 'KSampler.steps') !== false) {
                                                    echo '4'; // 生成步数默认值
                                                } elseif (strpos($intField, 'EmptySD3LatentImage.width') !== false) {
                                                    echo '768'; // 宽度默认值
                                                } elseif (strpos($intField, 'EmptySD3LatentImage.height') !== false) {
                                                    echo '1280'; // 高度默认值
                                                } elseif (strpos($intField, 'EmptySD3LatentImage.batch_size') !== false) {
                                                    echo '1'; // 批次默认值
                                                } else {
                                                    echo '4'; // 默认值
                                                }
                                            }
                                        ?>" step="1" class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-dark-500 bg-gray-50 dark:bg-dark-600 input-focus dark:text-white mb-4">
                                            <label for="int_field_<?php echo $index; ?>" class="block text-sm font-medium mb-1 field-mapping-label">整数参数字段映射</label>
                                            <input type="text" id="int_field_<?php echo $index; ?>" name="int_field[<?php echo $index; ?>]" value="<?php echo htmlspecialchars($intField); ?>" placeholder="如: 205:PrimitiveInt.value" class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-dark-500 bg-gray-50 dark:bg-dark-600 input-focus dark:text-white field-mapping-input">
                                        </div>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <!-- 兼容旧版本，只显示一个整数参数 -->
                                    <div id="int_group" style="display: <?php echo $currentConfig['int'] ? 'block' : 'none'; ?>;">
                                        <label id="int_label" for="int_value" class="block text-sm font-medium mb-1">
                                            <?php 
                                            // 根据字段类型设置标题
                                            if (!empty($currentConfig['int_field'])) {
                                                if (strpos($currentConfig['int_field'], 'SDXLEmptyLatentSizePicker+.batch_size') !== false) {
                                                    echo '整数参数（生成批次数）';
                                                } elseif (strpos($currentConfig['int_field'], 'PrimitiveInt.value') !== false) {
                                                    echo '整数参数（最大像素）';
                                                } elseif (strpos($currentConfig['int_field'], 'KSampler.steps') !== false) {
                                                    echo '整数参数（生成步数）';
                                                } elseif (strpos($currentConfig['int_field'], 'EmptySD3LatentImage.width') !== false) {
                                                    echo '整数参数（宽度）';
                                                } elseif (strpos($currentConfig['int_field'], 'EmptySD3LatentImage.height') !== false) {
                                                    echo '整数参数（高度）';
                                                } elseif (strpos($currentConfig['int_field'], 'EmptySD3LatentImage.batch_size') !== false) {
                                                    echo '整数参数（批次）';
                                                } else {
                                                    echo '整数参数';
                                                }
                                            } else {
                                                echo '整数参数';
                                            }
                                            ?>
                                        </label>
                                        <input type="number" id="int_value" name="int_value" value="<?php 
                                            // 根据字段类型设置默认值
                                            if (!empty($currentConfig['int_field'])) {
                                                if (isset($defaultConfig['input_values'][$currentConfig['int_field']])) {
                                                    echo (int)$defaultConfig['input_values'][$currentConfig['int_field']];
                                                } else {
                                                    // 设置不同字段类型的默认值
                                                    if (strpos($currentConfig['int_field'], 'SDXLEmptyLatentSizePicker+.batch_size') !== false) {
                                                        echo '4'; // 生成批次数默认值
                                                    } elseif (strpos($currentConfig['int_field'], 'PrimitiveInt.value') !== false) {
                                                        echo '3072'; // 最大像素默认值
                                                    } elseif (strpos($currentConfig['int_field'], 'KSampler.steps') !== false) {
                                                        echo '4'; // 生成步数默认值
                                                    } elseif (strpos($currentConfig['int_field'], 'EmptySD3LatentImage.width') !== false) {
                                                        echo '768'; // 宽度默认值
                                                    } elseif (strpos($currentConfig['int_field'], 'EmptySD3LatentImage.height') !== false) {
                                                        echo '1280'; // 高度默认值
                                                    } elseif (strpos($currentConfig['int_field'], 'EmptySD3LatentImage.batch_size') !== false) {
                                                        echo '1'; // 批次默认值
                                                    } else {
                                                        echo '4'; // 默认值
                                                    }
                                                }
                                            } else {
                                                echo '4'; // 默认值
                                            }
                                        ?>" step="1" class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-dark-500 bg-gray-50 dark:bg-dark-600 input-focus dark:text-white mb-4">
                                        <label for="int_field" class="block text-sm font-medium mb-1 field-mapping-label">整数参数字段映射</label>
                                        <input type="text" id="int_field" name="int_field" value="<?php echo htmlspecialchars($currentConfig['int_field']); ?>" placeholder="如: 205:PrimitiveInt.value" class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-dark-500 bg-gray-50 dark:bg-dark-600 input-focus dark:text-white field-mapping-input">
                                    </div>
                                <?php endif; ?>
                                
                                <!-- 分辨率下拉菜单 -->
                                <div id="resolution_group" style="display: <?php echo $currentConfig['resolution'] ? 'block' : 'none'; ?>;">
                                    <label for="resolution_value" class="block text-sm font-medium mb-1">图片尺寸</label>
                                    <select id="resolution_value" name="resolution_value" class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-dark-500 bg-gray-50 dark:bg-dark-600 input-focus dark:text-white mb-4">
                                        <?php foreach ($resolutionData as $resolution): ?>
                                            <option value="<?php echo htmlspecialchars($resolution); ?>" <?php echo (isset($defaultConfig['input_values'][$currentConfig['resolution_field']]) && $defaultConfig['input_values'][$currentConfig['resolution_field']] === $resolution) ? 'selected' : ''; ?>><?php echo htmlspecialchars($resolution); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <label for="resolution_field" class="block text-sm font-medium mb-1 field-mapping-label">图片尺寸字段映射</label>
                                    <input type="text" id="resolution_field" name="resolution_field" value="<?php echo htmlspecialchars($currentConfig['resolution_field']); ?>" placeholder="如: 97:SDXLEmptyLatentSizePicker+.resolution" class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-dark-500 bg-gray-50 dark:bg-dark-600 input-focus dark:text-white field-mapping-input">
                                </div>
                                <!-- 尺寸下拉菜单 -->
                                <div id="size_group" style="display: <?php echo $currentConfig['size'] ? 'block' : 'none'; ?>;">
                                    <label for="size_value" class="block text-sm font-medium mb-1">尺寸</label>
                                    <select id="size_value" name="size_value" class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-dark-500 bg-gray-50 dark:bg-dark-600 input-focus dark:text-white mb-4">
                                        <?php foreach ($sizeData as $size): ?>
                                            <option value="<?php echo htmlspecialchars($size); ?>" <?php echo (isset($defaultConfig['input_values'][$currentConfig['size_field']]) && $defaultConfig['input_values'][$currentConfig['size_field']] === $size) ? 'selected' : ''; ?>><?php echo htmlspecialchars($size); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <label for="size_field" class="block text-sm font-medium mb-1 field-mapping-label">尺寸字段映射</label>
                                    <input type="text" id="size_field" name="size_field" value="<?php echo htmlspecialchars($currentConfig['size_field']); ?>" placeholder="如: 20:BizyAir_Seedream4.size" class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-dark-500 bg-gray-50 dark:bg-dark-600 input-focus dark:text-white field-mapping-input">
                                </div>
                            </div>
                        </div>
                        
                    </form>
                    <div class="bg-white dark:bg-dark-700 rounded-xl shadow-md p-6 card-hover">
                            <h2 class="text-2xl font-bold mb-4 flex items-center"><i class="fa fa-cogs text-primary mr-2"></i>自定义参数</h2>

                            <?php if (!empty($stylesData)): ?>
                            <!-- CSV提示词选择区域 -->
                            <div class="mb-6 p-4 bg-gray-50 dark:bg-dark-600 rounded-lg prompt-template-section">
                                <h3 class="text-lg font-semibold mb-4 flex items-center">
                                    <i class="fa fa-list-alt text-primary mr-2"></i>
                                    提示词模板选择
                                </h3>

                                <!-- 第一行：下拉菜单和使用按钮 -->
                                <div class="flex gap-4 mb-4">
                                    <div class="flex-1">
                                        <label for="styleSelector" class="block text-sm font-medium mb-1">选择提示词模板，点击 提示词使用 会自动将提示词填充到上方文本提示词文本输入框</label>
                                        <select id="styleSelector" class="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-dark-500 bg-gray-50 dark:bg-dark-600 input-focus dark:text-white">
                                            <option value="">请选择一个提示词模板...</option>
                                            <?php foreach ($stylesData as $index => $style): ?>
                                                <option value="<?php echo $index; ?>">
                                                    <?php echo htmlspecialchars($style['name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="flex items-end">
                                        <button type="button" id="usePromptBtn" class="px-6 py-2 bg-primary hover:bg-primary/90 text-white font-medium rounded-lg transition-colors flex items-center">
                                            <i class="fa fa-magic mr-2"></i>
                                            提示词使用
                                        </button>
                                    </div>
                                </div>

                                <!-- 第二行：说明和图片显示区域 -->
                                <div id="remarkSection" class="hidden remark-section">
                                    <div class="mb-3">
                                        <h4 class="text-sm font-semibold mb-2 text-gray-700 dark:text-gray-300">说明：</h4>
                                        <div id="remarkText" class="text-sm text-gray-600 dark:text-gray-400 bg-blue-50 dark:bg-blue-900/20 p-3 rounded border border-blue-200 dark:border-blue-800 break-words overflow-wrap-anywhere"></div>
                                    </div>
                                    <div id="remarkImageContainer" class="hidden">
                                        <h4 class="text-sm font-semibold mb-2 text-gray-700 dark:text-gray-300">示例图片：</h4>
                                        <div class="border border-gray-200 dark:border-dark-500 rounded-lg overflow-hidden">
                                            <img id="remarkImage" src="" alt="示例图片" class="w-full h-auto max-h-100 object-contain bg-gray-50 dark:bg-dark-600">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                    </div>
                </div>
                
                <div class="space-y-6 animate-slide-up" style="animation-delay: 0.2s">
                    <div class="bg-white dark:bg-dark-700 rounded-xl shadow-md p-6 card-hover">
                        <h2 class="text-2xl font-bold mb-4 flex items-center"><i class="fa fa-image text-primary mr-2"></i>生成结果</h2>
                        <div class="mb-6">
                            <?php if ($response && !empty($response['data']['outputs'])): ?>
                                <?php 
                                // 获取所有生成的图片URL
                                $images = [];
                                if (!empty($response['data']['outputs']) && is_array($response['data']['outputs'])) {
                                    foreach ($response['data']['outputs'] as $output) {
                                        if (!empty($output['object_url'])) {
                                            $images[] = $output['object_url'];
                                        }
                                    }
                                }
                                ?>
                                
                                <?php if (count($images) > 1): ?>
                                    <!-- 多张图片轮播显示 -->
                                    <div class="relative rounded-lg overflow-hidden border border-gray-200 dark:border-dark-500">
                                        <!-- 图片容器 -->
                                        <div id="imageCarousel" class="relative w-full">
                                            <?php foreach ($images as $index => $imageUrl): ?>
                                                <div class="carousel-item <?php echo $index === 0 ? 'block' : 'hidden'; ?> w-full">
                                                    <img src="<?php echo htmlspecialchars($imageUrl); ?>" alt="生成的图片 <?php echo $index + 1; ?>" class="w-full h-auto">
                                                    <!-- 下载按钮 -->
                                                    <a href="<?php echo htmlspecialchars($imageUrl); ?>" target="_blank" download class="absolute bottom-4 right-4 bg-primary/90 hover:bg-primary text-white p-2 rounded-full transition-colors">
                                                        <i class="fa fa-download"></i>
                                                    </a>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                        
                                        <!-- 轮播指示器 -->
                                        <div class="absolute bottom-4 left-1/2 transform -translate-x-1/2 flex space-x-2">
                                            <?php for ($i = 0; $i < count($images); $i++): ?>
                                                <button onclick="showImage(<?php echo $i; ?>)" class="w-3 h-3 rounded-full <?php echo $i === 0 ? 'bg-white' : 'bg-white/50'; ?>" aria-label="切换到图片 <?php echo $i + 1; ?>"></button>
                                            <?php endfor; ?>
                                        </div>
                                        
                                        <!-- 上一张/下一张按钮 -->
                                        <button onclick="prevImage()" class="absolute left-4 top-1/2 transform -translate-y-1/2 bg-black/30 hover:bg-black/50 text-white p-2 rounded-full transition-colors">
                                            <i class="fa fa-chevron-left"></i>
                                        </button>
                                        <button onclick="nextImage()" class="absolute right-4 top-1/2 transform -translate-y-1/2 bg-black/30 hover:bg-black/50 text-white p-2 rounded-full transition-colors">
                                            <i class="fa fa-chevron-right"></i>
                                        </button>
                                    </div>
                                <?php elseif (count($images) === 1): ?>
                                    <!-- 单张图片显示 -->
                                    <div class="relative rounded-lg overflow-hidden border border-gray-200 dark:border-dark-500">
                                        <img src="<?php echo htmlspecialchars($images[0]); ?>" alt="生成的图片" class="w-full h-auto">
                                        <a href="<?php echo htmlspecialchars($images[0]); ?>" target="_blank" download class="absolute bottom-4 right-4 bg-primary/90 hover:bg-primary text-white p-2 rounded-full transition-colors">
                                            <i class="fa fa-download"></i>
                                        </a>
                                    </div>
                                <?php else: ?>
                                    <div class="bg-gray-100 dark:bg-dark-600 rounded-lg p-8 text-center">
                                        <i class="fa fa-picture-o text-5xl text-gray-400 mb-2"></i>
                                        <p class="text-gray-500 dark:text-gray-400">未生成图片</p>
                                    </div>
                                <?php endif; ?>
                            <?php elseif ($response && !empty($response['image'])): ?>
                                <!-- 兼容旧版本，只有一张图片 -->
                                <div class="relative rounded-lg overflow-hidden border border-gray-200 dark:border-dark-500">
                                    <img src="<?php echo htmlspecialchars($response['image']); ?>" alt="生成的图片" class="w-full h-auto">
                                    <a href="<?php echo htmlspecialchars($response['image']); ?>" target="_blank" download class="absolute bottom-4 right-4 bg-primary/90 hover:bg-primary text-white p-2 rounded-full transition-colors">
                                        <i class="fa fa-download"></i>
                                    </a>
                                </div>
                            <?php else: ?>
                                <div class="bg-gray-100 dark:bg-dark-600 rounded-lg p-8 text-center">
                                    <i class="fa fa-picture-o text-5xl text-gray-400 mb-2"></i>
                                    <p class="text-gray-500 dark:text-gray-400">图片将显示在这里</p>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div id="result_status" class="mb-6">
                            <?php if ($response): ?>
                                <?php if ($response['status'] == 'success'): ?>
                                    <div class="bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-300 p-4 rounded-lg"><div class="font-mono text-sm whitespace-pre-line break-words overflow-x-auto leading-relaxed"><?php echo htmlspecialchars($response['message']); ?></div></div>
                                <?php elseif ($response['status'] == 'warning'): ?>
                                    <div class="bg-yellow-100 dark:bg-yellow-900/30 text-yellow-800 dark:text-yellow-300 p-4 rounded-lg"><div class="font-mono text-sm whitespace-pre-line break-words overflow-x-auto leading-relaxed"><?php echo htmlspecialchars($response['message']); ?></div></div>
                                <?php else: ?>
                                    <div class="bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-300 p-4 rounded-lg"><div class="font-mono text-sm whitespace-pre-line break-words overflow-x-auto leading-relaxed"><?php echo htmlspecialchars($response['message']); ?></div></div>
                                <?php endif; ?>
                            <?php else: ?>
                                <div class="bg-gray-100 dark:bg-dark-600 text-gray-800 dark:text-gray-200 p-4 rounded-lg"><i class="fa fa-info-circle mr-2"></i>请配置密钥参数后，再点击"生成图片"按钮开始处理</div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="bg-white dark:bg-dark-700 rounded-xl shadow-md p-6 card-hover hidden">
                        <h2 class="text-2xl font-bold mb-4 flex items-center"><i class="fa fa-code text-primary mr-2"></i>API响应详情</h2>
                        <div class="bg-gray-50 dark:bg-dark-600 rounded-lg p-4 max-h-64 overflow-auto font-mono text-sm">
                            <?php if ($response && !empty($response['data'])): ?>
                                <pre><?php echo htmlspecialchars(json_encode($response['data'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)); ?></pre>
                            <?php else: ?>
                                <p class="text-gray-500 dark:text-gray-400">API响应将显示在这里</p>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div id="instructions" class="bg-white dark:bg-dark-700 rounded-xl shadow-md p-6 card-hover">
                        <h2 class="text-2xl font-bold mb-4 flex items-center"><i class="fa fa-book text-primary mr-2"></i>使用说明</h2>
                        <div class="space-y-4 text-sm">
                            <div>
                                <h3 class="font-semibold text-lg mb-2">功能说明：</h3>
                                <div class="flex items-center p-3 bg-primary/10 rounded-lg">
                                <p class="list-disc pl-5 space-y-1"><i class="fa fa-info-circle text-primary mr-2"></i><?php echo nl2br(htmlspecialchars($defaultConfig['info'] ?? '此模型没有提供详细说明。')); ?></p>
                                 </div>

                            </div>
                            <div>
                                <h3 class="font-semibold text-lg mb-2">图片输入方式：</h3>
                                <ul class="list-disc pl-5 space-y-1">
                                    <li><strong>本地上传优先</strong>：如果某个图片位置同时上传了本地文件并输入了URL，将优先使用本地文件。</li>
                                    <li><strong>二选一</strong>：每个图片位置请只选择一种方式输入（本地上传 或 URL）。</li>
                                </ul>
                            </div>
                            <div class="p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
                                <i class="fa fa-lightbulb-o text-yellow-500 mr-2"></i>
                                <strong>提示</strong>：从左侧菜单 或者 下方API模板展示 窗口中选择不同的API模板，此处的表单会自动更新以匹配模板所需的输入参数。
                                
                            </div>
                            <div class="flex gap-3">
                                <div class="flex-1 p-3 flex items-center justify-center space-x-2 bg-orange-500 hover:bg-orange-600 text-white rounded-lg transition-colors">
                                    <a href="https://bizyair.cn/community/app/<?php echo $Bid; ?>" target="_blank" class="flex items-center space-x-2">
                                        <i class="fa fa-chevron-right"></i>
                                        <span>访问本AI应用 BizyAIR官方API</span>
                                        <i class="fa fa-chevron-left"></i>
                                    </a>
                                </div>
                                <div class="p-3 flex items-center justify-center space-x-2 bg-orange-500 hover:bg-orange-600 text-white rounded-lg transition-colors cursor-pointer" onclick="openTemplateModal()">
                                    <i class="fa fa-th-large"></i>
                                    <span>API模板展示</span>
                                </div>
                            </div>
                            
                        </div>
                    </div>
                </div>
            </section>
        </main>
    </div>

    <!-- 模板展示弹出窗口 -->
    <div id="templateModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50 flex items-center justify-center p-4">
        <div class="bg-white dark:bg-dark-700 rounded-xl max-w-6xl w-full max-h-[90vh] overflow-hidden">
            <div class="p-6 border-b border-gray-200 dark:border-dark-600">
                <div class="flex items-center justify-between">
                    <h2 class="text-2xl font-bold flex items-center">
                        <i class="fa fa-th-large text-orange-500 mr-3"></i>
                        BizyAIR 模板展示
                    </h2>
                    <button onclick="closeTemplateModal()" class="p-2 hover:bg-gray-100 dark:hover:bg-dark-600 rounded-lg transition-colors">
                        <i class="fa fa-times text-xl"></i>
                    </button>
                </div>
            </div>

            <div class="p-6 overflow-y-auto max-h-[calc(90vh-120px)]">
                <div id="templateGrid" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-5 gap-6">
                    <!-- 模板卡片将通过JavaScript动态生成 -->
                </div>
            </div>
        </div>
    </div>

    <script src="BizyAIR.js"></script>
</body>
</html>